var createError = require('http-errors');
var express = require('express');
var path = require('path');

//导入session插件
const session = require("express-session")({
  secret:'keyboard cat',
  cookie:{maxAge:60000}
});

var cookieParser = require('cookie-parser');
var logger = require('morgan');


//创建socket.io-session插件
var iosession = require("express-socket.io-session")(session);

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

var server = require("http").Server(app);//将app转换为http对象
var io = require('socket.io')(server);//将server和socket.io关联
server.listen(3000);//使服务器监听3000端口

io.use(iosession);//socket.io使用session插件

io.on("connection",function(socket){
  console.log("Someone connected");
  // socket.on("req",function(data){
  //   console.log(data);
  // });
  socket.on("join",data=>{//显示登录成功的用户的账户名
    const name = socket.handshake.session.user.loginname;
    socket.handshake.session.save();
    io.emit("announcement",name+" joined the chat.");
  });

  socket.on("say", data=>{
    const name = socket.handshake.session.user.loginname;
    socket.handshake.session.save();
    io.emit("newsay", name + " : " + data + "    (创建时间："+ new Date() +")");
  })
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session);//为express应用程序加入session中间件
app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// module.exports = app;
